//
//  QQManager.m
//  6p
//
//  Created by weienjie on 15/3/2.
//  Copyright (c) 2015年 fenfen. All rights reserved.
//

#import "QQManager.h"
//#import "CommonHeader.h"
//#import "CustomTools.h"
#import "LoginManager.h"
//#import "TencentOAuth.h"
#import <TencentOpenAPI/TencentOAuth.h>

#define kOpenID                 @"qq_openid"
#define kTencent_AccessToken    @"qq_accessToken"
#define kTencent_ExpireDate     @"qq_expireDate"


#define QZone_AppKey    @"1104778948"
static QQManager *intance = nil;

@interface QQManager ()
{
    BOOL qqlogin;
}
@end

@implementation QQManager

//单例
+ (id)sharedInstance
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken,^{intance = [[QQManager alloc] init];});
    
    return intance;
}

+(id)alloc
{
    if (!intance)
    {
        return [super alloc];
    }
    return [self sharedInstance];
}

- (id)init
{
    if (self = [super init])
    {
        [self readTencentAuthorizInfo];
    }
    return self;
}

//检测qq是否安装
+ (BOOL)isQQInstanlled
{
    NSLog(@"检测qq是否安装");
    return [TencentOAuth iphoneQQInstalled];
}

#pragma mark - Tencent

- (void)qqAuth
{
    TencentOAuth *auth = [[TencentOAuth alloc] initWithAppId:QZone_AppKey andDelegate:self];
    [[QQManager sharedInstance] setTencentAuth:auth];
    [auth authorize:[NSArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil]  inSafari:NO];
}

//登录qq
- (void)qqLogin
{
    qqlogin = YES;
    //重新授权
    [self qqAuth];
}

- (void)qqAutoLogin
{
    NSDictionary *dict = @{@"sex":@"", @"nickname":@"", @"city":@"", @"headimgurl":@"", @"province":@""};
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"json data:%@",json);
    
    NSMutableDictionary *pra = [NSMutableDictionary dictionary];
    [pra setValue:@"qq" forKey:@"type"];
    [pra setValue:_tencent_OpenID forKey:@"openid"];
    [pra setValue:json forKey:@"info"];
    [pra setValue:_tencent_AccessToken forKey:@"access_token"];
    
    [LoginManager loginWithData:pra type:LoginType_qq];
}

- (void)getQQ_UserInfo
{
    [self.tencentAuth getUserInfo];
}

//QQ退出登录
- (void)qqLogout
{
    [self.tencentAuth logout:self];
    [self clearTencentAuthorizInfo];
}

//分享到QQ
- (void)shareToQQ:(QQApiObject *)data
{
    if (![_tencentAuth isSessionValid])
    {
        [self qqAuth];
    }
    else
    {
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:data];
        QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        [self handleSendResult:sent];
    }
}


- (void)shareToQzone:(QQApiObject *)data
{
    if ([self isTencentAuthorizeExpired])
    {
        [self qqAuth];
    }
    else
    {
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:data];
        QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
        [self handleSendResult:sent];
    }
}


- (void)inviteToQQ:(id)data
{
    
}


- (BOOL)isTencentAuthorizeExpired
{
    if (!self.tencent_ExpirationDate || [[NSDate date] timeIntervalSince1970] > [self.tencent_ExpirationDate timeIntervalSince1970])
    {
        self.tencent_OpenID = nil;
        self.tencent_AccessToken = nil;
        self.tencent_ExpirationDate = nil;
        self.tencentAuth = nil;
        return YES;
    }
    return NO;
}

- (void)saveTencentAuthorizInfo
{
    [[NSUserDefaults standardUserDefaults] setObject:self.tencent_OpenID forKey:kOpenID];
    [[NSUserDefaults standardUserDefaults] setObject:self.tencent_AccessToken forKey:kTencent_AccessToken];
    [[NSUserDefaults standardUserDefaults] setObject:self.tencent_ExpirationDate forKey:kTencent_ExpireDate];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

- (void)readTencentAuthorizInfo
{
    self.tencent_OpenID = [[NSUserDefaults standardUserDefaults] objectForKey:kOpenID];
    self.tencent_AccessToken = [[NSUserDefaults standardUserDefaults] objectForKey:kTencent_AccessToken];
    self.tencent_ExpirationDate = [[NSUserDefaults standardUserDefaults] objectForKey:kTencent_ExpireDate];
}

- (void)clearTencentAuthorizInfo
{
    self.tencentAuth = nil;
    self.tencent_OpenID = nil;
    self.tencent_AccessToken = nil;
    self.tencent_ExpirationDate = nil;
    
    [self saveTencentAuthorizInfo];
}


- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    if (sendResult != EQQAPISENDSUCESS)
    {
        [self qqAuth];

    }
}

#pragma mark - TencentSessionDelegate

/**
 * 登录成功后的回调
 */
- (void)tencentDidLogin
{
    [self setTencent_OpenID:[self tencentAuth].openId];
    [self setTencent_AccessToken:[self tencentAuth].accessToken];
    [self setTencent_ExpirationDate:[self tencentAuth].expirationDate];
    [self saveTencentAuthorizInfo];
    
    if (qqlogin)
    {
        [self.tencentAuth getUserInfo];
    }
}

/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork
{
}

/**
 * 获取用户个人信息回调
 * \param response API返回结果，具体定义参见sdkdef.h文件中\ref APIResponse
 * \remarks 正确返回示例: \snippet example/getUserInfoResponse.exp success
 *          错误返回示例: \snippet example/getUserInfoResponse.exp fail
 */
- (void)getUserInfoResponse:(APIResponse*) response
{
    NSDictionary *json = response.jsonResponse;
    if (!json) {
//        [CustomTools showTipViewWithText:@"无法获取第三方用户信息"];
        return;
    }
    NSMutableDictionary *pra = [NSMutableDictionary dictionaryWithDictionary:json];
    [pra setValue:self.tencent_OpenID forKey:@"user_unique_id"];
    [pra setValue:[self tencentAuth].accessToken forKey:@"access_token"];
    [LoginManager loginWithData:pra type:LoginType_qq];

}


/**
 * 退出登录的回调
 */
- (void)tencentDidLogout
{
    [self clearTencentAuthorizInfo];
}
#pragma mark - QQApiInterfaceDelegate
/**
 处理来至QQ的请求
 */
- (void)onReq:(QQBaseReq *)req
{
}

/**
 处理来至QQ的响应
 */
- (void)onResp:(QQBaseResp *)resp
{
    if (resp.result.integerValue == 0)
    {
//        [CustomTools showTipViewWithText:@"分享成功"];
    }
    else if (resp.result.integerValue != -4)
    {
//        [CustomTools showTipViewWithText:@"分享失败"];
    }
}

/**
 处理QQ在线状态的回调
 */
- (void)isOnlineResponse:(NSDictionary *)response
{
    
    
    
}

@end
